# coding=utf-8
from random import randrange
import pygame
pygame.init()
screen = pygame.display.set_mode((500,500))
shenzi = [pygame.Rect(10,10, 10, 10)]
screen.fill((138,43,226))
up = (0, -10)
down = (0, 10)
left = (-10, 0)
right = (10, 0)
move = down
clock = pygame.time.Clock()
food = None
score = 0
font = pygame.font.SysFont('simhei', 20)
die = False
while True:
    clock.tick(min(10 + (len(shenzi) / 2), 30))
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        pygame.quit()
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP and move != down:
            move = up
        if event.key == pygame.K_DOWN and move != up:
            move = down
        if event.key == pygame.K_LEFT and move != right:
            move = left
        if event.key == pygame.K_RIGHT and move != left:
            move = right
    screen.fill((147,112,219))
    if die:
    	screen.fill((0, 0, 0))
    	surface = font.render(u"Game Over 分数:" + str(score), True, (220,20,60))
    	screen.blit(surface, (250, 0))
    	pygame.display.flip()
    	continue
    if food is None:
        food = pygame.Rect(randrange(50) * 10, randrange(50) * 10, 10, 10)
    pygame.draw.rect(screen, (255,255,0), food)
    for rect in shenzi:
        pygame.draw.rect(screen, (255,255,240), rect)
    node = shenzi[-1].move(move)
    if node in shenzi or node.left > 500 or node.top > 500 or node.left < 0 or node.top < 0:
        die = True
        continue
    if node == food:
        food = None
        score = score + 10
    else:
        del shenzi[0]
    shenzi.append(node)
    surface = font.render(u'分数'+str(score), True, (0,0,0))
    screen.blit(surface,(420,0))
    pygame.display.flip()
